package yxy.game.pm2.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.Sign;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.module.NotificationHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.playtype.PlayTypeHandle;
import yxy.game.pm2.module.playtype.PlayTypeModule;

/** 玩家 更改称号 */
@MessageType(proto = Command.PlayerTitleChange, classtype = PlayerMessage.PlayerTitleChangeRequest.class)
public class CMD_PlayerTitleChange extends Command<PlayerMessage.PlayerTitleChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, PlayerMessage.PlayerTitleChangeRequest request) {
		String playerCode = messageSource.getTag();
		int title = request.getTitle();

		PlayerMessage.PlayerTitleChangeResponse.Builder response = PlayerMessage.PlayerTitleChangeResponse.newBuilder();

		if (title > 0 && !Sign.exist(playerCode, CurrencyType.CT_称号, title)) {
			send(messageSource, response, Result.PlayerTitleNotGet);
			return;
		}
		PlayerBean playerBean = PlayerBean.get(playerCode);
		try {
			if (playerBean.tryLock()) {
				playerBean.setTitle(title);
				playerBean.set();

				response.setTitle(playerBean.getTitle());

				PlayTypeHandle.saveTitle(playerCode, PlayTypeModule.get(playerCode));
				new NotificationHandle().notifyPlayerTitle(playerBean);
				new BattleHandle().powerUpdate(playerCode);
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerBean.unlock();
		}
	}

	private void send(MessageSource messageSource, PlayerMessage.PlayerTitleChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}